package com.ineast.poi.controller;

import com.ineast.common.response.Result;
import com.ineast.poi.service.CreateExcelTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @description: TODO
 * @author: liu-jj
 * @date: 2021/12/4 16:57
 */
@RestController
@RequestMapping("download")
@Slf4j
public class ExcelController {
    @Autowired
    private CreateExcelTemplateService createExcelTemplateService;

    @GetMapping("excel/template/{filename}")
    public Result getExcelTemplate(HttpServletResponse response, @PathVariable("filename") String fileName){
        // 输出Excel文件
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            createExcelTemplateService.createExcelTemplate(wb);
            OutputStream output = response.getOutputStream();
            // 清除空白行
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            wb.write(output);
            output.close();
            return Result.ok().message(fileName + "下载成功");
        }catch (IOException e){
            e.printStackTrace();
            return Result.error().message(fileName + "下载失败");
        }
    }

    @GetMapping("/excel")
    public Result downloadWorkHourRecordTemplate(HttpServletResponse response, String filename) {

        try {
            createExcelTemplateService.createExcelTemplate(filename);
            Resource resource = new ClassPathResource("/file/" + filename + ".xls");
            String filePath = "/file/" + filename + ".xls";
            File file = new File("/file/" + filename + ".xls");
            log.info("文件路径:{" + filePath + "}是否存在:{}:" , file.exists());
            // 通过流将文件复制到file中
            FileUtils.copyToFile(resource.getInputStream(), file);
//            ClassPathResource classPathResource = new ClassPathResource("/file/"+filename+".xlsx");
//            File file = classPathResource.getFile();
            InputStream inputStream = new FileInputStream(file);
            //强制下载不打开
            // response.setContentType("application/force-download");
            response.setContentType("application/msexcel;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename + ".xls", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }

            }
            inputStream.close();
            out.close();
            out.flush();
            return Result.ok().message(filename + "下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message(filename + "下载失败");
        }
    }
}
